<template>
  <n-modal :show="state.dialogFormVisible" @onUpdateShow="close">
    <div class="name-auth-dia">
      <div class="nav">
        <div class="title">修改邮箱</div>
        <div class="close" @click="close">
          <i class="landscape landscape-guanbi"></i>
        </div>
      </div>
      <div class="con">
        <NForm
          ref="ruleForm"
          :show-label="false"
          :model="queryForm"
          show-feedback
          :rules="rules"
        >
          <n-form-item label="原邮箱" path="rawEmail">
            <n-input
              disabled
              v-model:value="queryForm.rawEmail"
              placeholder="请输入邮箱"
            />
          </n-form-item>
          <n-form-item label="新邮箱" path="email">
            <n-input v-model:value="queryForm.email" placeholder="请输入邮箱" />
          </n-form-item>
          <n-form-item label="验证码" path="smsCode">
            <div class="flex align-center w-full">
              <n-input
                style="flex: 1"
                v-model:value="queryForm.smsCode"
                placeholder="请输入验证码"
              />
              <NButton
                :disabled="codeTime !== 60"
                @click="handGetCode"
                class="code-btn"
                type="primary"
                attr-type="button"
              >
                <span v-if="codeTime === 60">获取验证码</span>
                <span v-else>{{ codeTime }}s后重新获取</span>
              </NButton>
            </div>
          </n-form-item>
        </NForm>
        <div class="tool flex">
          <n-button class="btn" @click="close">取消</n-button>
          <n-button
            class="btn confirm-btn"
            type="primary"
            :disabled="submitDis"
            @click="handleValidateClick"
          >
            确认
          </n-button>
        </div>
      </div>
    </div>
  </n-modal>
</template>
<script setup lang="ts">
import { NButton, NForm, NFormItem, NInput, NModal } from 'naive-ui'
import type { FormRules, FormItemRule, FormInst } from 'naive-ui'
import { computed, reactive, ref } from 'vue'
import valiDate from '@/utils/validate'
import loginApi from '@/service/api/login'
import { useAppsStore } from '@/stores/modules/app'

const emit = defineEmits(['success'])
const submitDis = computed(() => {
  return !queryForm.value.rawEmail
})
const useStore = useAppsStore()
const { doUserInfo } = useStore
const { getUserInfo: userInfo } = storeToRefs(useStore)
const queryForm = ref({
  rawEmail: '',
  email: '',
  smsCode: ''
})
const codeTime = ref(60)
let requestLoading = false
const handGetCode = async () => {
  const email = queryForm.value.email
  if (!email) {
    msgUtil.$message.error('邮箱不能为空')
    return
  }
  if (!valiDate.isEmail(email)) {
    msgUtil.$message.error('邮箱格式不正确')
    return
  }
  if (email === queryForm.value.rawEmail) {
    msgUtil.$message.error('不能和原邮箱相同')
    return
  }
  if (requestLoading) return
  requestLoading = true
  const { code, msg } = await loginApi.sendCode({
    email: email,
    type: 'email'
  })
  if (code !== 0) {
    requestLoading = false
    msgUtil.$message.error(msg)
    return
  }

  msgUtil.$message.success('验证码已发送到您的邮箱')
  requestLoading = false
  const timer = setInterval(() => {
    codeTime.value--
    if (codeTime.value <= 0) {
      clearInterval(timer)
      codeTime.value = 60
    }
  }, 1000)
}

function validateCellphoneSame(rule: FormItemRule, value: string): boolean {
  return value !== queryForm.value.rawEmail
}

const rules: FormRules = {
  rawEmail: [
    {
      required: true,
      message: '原邮箱不能为空',
      trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      message: '邮箱不能为空',
      trigger: 'blur'
    },
    {
      validator: validateCellphoneSame,
      message: '不能和原邮箱相同',
      trigger: ['blur', 'password-input']
    }
  ],
  smsCode: [
    {
      required: true,
      message: '验证码不能为空',
      trigger: 'blur'
    }
  ]
}
const ruleForm = ref<FormInst | null>(null)
const handleValidateClick = (e: MouseEvent) => {
  e.preventDefault()
  ruleForm.value?.validate((errors: any) => {
    if (!errors) {
      save()
    }
  })
}

const save = async () => {
  if (requestLoading) return
  requestLoading = true
  const { code, msg } = await loginApi.updemail(queryForm.value)
  if (code !== 0) {
    requestLoading = false
    msgUtil.$message.error(msg)
    return
  }
  msgUtil.$message.success('换绑成功')
  doUserInfo()
  emit('success')
  close()
  requestLoading = false
}
const state = reactive({
  dialogFormVisible: false
})
const close = () => {
  queryForm.value = {
    rawEmail: '',
    email: '',
    smsCode: ''
  }
  state.dialogFormVisible = false
}
const open = () => {
  queryForm.value.rawEmail = userInfo.value?.email || ''
  state.dialogFormVisible = true
}
defineExpose({
  open
})
</script>

<style scoped lang="scss">
.name-auth-dia {
  width: 476px;
  background: #fff;
  border-radius: 15px;
  box-sizing: border-box;
  padding: 24px;

  .nav {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #eee;
    padding-bottom: 24px;

    .title {
      font-size: 18px;
      font-weight: bold;
      color: #333333;
    }

    .close {
      cursor: pointer;

      i {
        font-size: 24px;
        color: #666666;
      }
    }
  }

  .con {
    padding-top: 24px;
  }

  .phone-prefix {
    font-size: 14px;
    font-weight: 400;
    color: #666666;
    padding-right: 10px;
    position: relative;

    &:before {
      content: '';
      position: absolute;
      top: 50%;
      right: 0px;
      transform: translateY(-50%);
      width: 0;
      height: 14px;
      border: 1px solid #999999;
    }
  }

  .code-btn {
    margin-left: 12px;
  }

  .tool {
    margin-top: 20px;
    justify-content: center;

    .btn {
      width: 124px;
      height: 40px;
    }

    .confirm-btn {
      margin-left: 24px;
    }
  }
}
</style>
